import Vue from 'vue'
import VueRouter from 'vue-router'
import Loginview from '../views/Loginview.vue'
import AdministratorView from '../components/AdministratorView.vue'
import store from '../store/index'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

// 配置NProgress
Nprogress.configure({
  easing: 'ease', // 动画方式
  speed: 500, // 递增进度条的速度
})

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'login',
    component: Loginview,
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/HomeView.vue'),
    children: [
      {
        path: '/home',
        name: 'MainView',
        component: () => import('../components/MainView.vue'),
      },
      {
        path: '/news/add',
        name: 'newsadd',
        component: () => import('../components/NewsAddView.vue'),
      },
      {
        path: '/news/add/:id',
        name: 'newsedit',
        component: () => import('../components/NewsAddView.vue'),
      },
      {
        path: '/stores/add',
        name: 'storesadd',
        component: () => import('../components/StoresAddView.vue'),
      },
      {
        path: '/administrator',
        name: 'administrator',
        component: AdministratorView,
      },
      {
        path: '/news',
        name: 'news',
        component: () => import('../components/NewsView.vue'),
      },
      {
        path: '/stores',
        name: 'stores',
        component: () => import('../components/StoresView.vue'),
      },
      {
        path: '/administratorrole',
        name: 'administratorrole',
        component: () => import('../components/AdministratorroleView.vue'),
      },
      {
        path: '/house',
        name: 'house',
        component: () => import('../components/HouseView.vue'),
      },
      {
        path: '/building',
        name: 'building',
        component: () => import('../components/BuildingView.vue'),
      },
      {
        path: '/fee',
        name: 'fee',
        component: () => import('../components/FeeView.vue'),
      },
      {
        path: '/questions',
        name: 'questions',
        component: () => import('../components/QuestionsView.vue'),
      },
      // 添加居民
      {
        path: '/userinfo',
        name: 'userinfo',
        component: () => import('../components/Userinfo.vue'),
      },
      // 添加报修
      {
        path: '/repairs',
        name: 'repairs',
        component: () => import('../components/Repairs.vue'),
      },
      {
        path: '/staffs',
        name: 'staffs',
        component: () => import('../components/SstaffsView.vue'),
      },
      {
        path: '/advertisement',
        name: 'advertisement',
        component: () => import('../components/AdvertisementView.vue'),
      },
      {
        path: '/member',
        name: 'member',
        component: () => import('../components/MemberView.vue'),
      },
    ],
  },
  {
    path: '/404',
    name: '404',
    component: () => import('../views/Loginview.vue'),
  },
  {
    path: '*',
    redirect: '/404',
  },
]

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}
const router = new VueRouter({
  routes,
})
// 在 router.beforeEach 中添加 Nprogress.start()
router.beforeEach((to, from, next) => {
  // 启动进度条
  Nprogress.start()

  let token = localStorage.getItem('token')

  // 定义"公开路由白名单"(无需 token 即可访问，如登录页、404页)
  const whiteList = ['/', '/login', '/404']

  // 如果没有token
  if (!token) {
    // 白名单路径直接通过，否则重定向到登录页
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
    return
  }

  // 已登录状态 - 检查是否正在访问登录页
  if (to.path === '/login') {
    next({ path: '/home' })
    return
  }

  // 已登录状态 - 检查是否已完成动态路由添加
  let isAddRouter = store.state.isAddRoute
  if (isAddRouter) {
    next()
    return
  }

  try {
    const asyncRouteList = store.getters.getParentMenu || []

    const validRoutes = asyncRouteList.filter((item) => item.url && item.url.trim() !== '')

    console.log('validRoutes', validRoutes)

    if (validRoutes.length === 0) {
      store.commit('setIsAddRoute', true)
      next(to.path === '/404' ? '/404' : '/home')
      return
    }

    // 创建一个集合来跟踪已添加的路由名称
    const addedRouteNames = new Set()

    // 先将静态路由名称添加到集合中
    routes.forEach((route) => {
      if (route.name) {
        addedRouteNames.add(route.name)
      }
      // 检查嵌套路由
      if (route.children) {
        route.children.forEach((child) => {
          if (child.name) {
            addedRouteNames.add(child.name)
          }
        })
      }
    })

    validRoutes.forEach((item) => {
      let routename = item.url.trim().substring(1)

      // 检查路由是否已经添加
      if (addedRouteNames.has(routename)) {
        console.warn(`路由 ${routename} 已存在，跳过添加`)
        return
      }

      // 添加路由到已添加集合
      addedRouteNames.add(routename)

      let componentname = routename.charAt(0).toUpperCase() + routename.slice(1)
      let dynamicRoute = {
        path: item.url,
        name: routename,
        component: () =>
          import(`@/views/${componentname}View.vue`).catch((err) => {
            console.error(`加载组件 ${componentname}View 失败:`, err)
            // 尝试加载组件失败时，使用默认组件
            return import('@/components/' + componentname + '.vue').catch(() => {
              return import('@/views/Loginview.vue')
            })
          }),
      }
      router.addRoute('home', dynamicRoute)
    })

    // 检查是否已经存在404路由
    const has404Route = router.options.routes.some((route) => route.children && route.children.some((child) => child.name === 'page404'))

    if (!has404Route) {
      router.addRoute('home', {
        path: '/404',
        name: 'page404',
        component: () => import('../views/Loginview.vue'),
        meta: { hidden: true },
      })
    }

    store.commit('setIsAddRoute', true)

    // 动态路由添加完成后，继续导航到目标路径
    next({ ...to, replace: true })
  } catch (error) {
    console.error('动态添加路由失败:', error)
    store.dispatch('clearstate')
    next('/login')
  }
})

// 添加 afterEach 钩子来结束进度条
router.afterEach(() => {
  // 结束进度条
  Nprogress.done()
})

export default router
